package com.sairui.Xiaoruilib.widgets;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.util.AttributeSet;
import android.view.View;

import cn.iyivi.R;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by sunqiyong on 2018/4/9.
 */

public class NewVoiceView extends View {
    private int mColor = Color.GREEN;//声音颜色
    private int mCancelColor;
    private float mSpaceBetween = 8;//两个声音线条之间的间距
    private float mWidth = 8;//线条宽度
    private Paint mPaint;
    private final int FB = 30;//最大的分贝值，根据讯飞语音得到
    //通过讯飞得知，声音分贝最高为30，所以这里没提升一个分贝，voiceLevel对应1-30之间的分贝值
    private int voiceLevel = 1;
    //每一个分贝值增加的线条高度
    private int voiceHeight = 1;

    private int mTotalCount;//要画的线条的个数的一半

    private List<Integer> mVoiceData = new ArrayList<Integer>();

    private Boolean FirstDraw = true;//是否第一次初始化

    private Boolean isThreadStart = false;//循环画线条线程是否开启

    private Boolean isEyesOpen = false;//机器人眼睛是否打开

    private Boolean isExit = false;//是否销毁

    private int mDrawLineTime = 90;//就是时间画线条的间隔时间

    private List<Integer> mCatchVoiceData = new ArrayList<Integer>();

    public NewVoiceView(Context context) {
        super(context);
    }

    private boolean isShowLine = true;


    @SuppressLint("HandlerLeak")
    private Handler mHander = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (isAllDeng()) {
                isThreadStart = false;
            }
            if(mCatchVoiceData.size() == 0){
                moveList(1);
            }else {
                moveList(mCatchVoiceData.get(0));
                mCatchVoiceData.remove(0);
            }
            invalidate();
            if(!isShowLine && isAllDeng() && mDismissLineListener != null){
                mDismissLineListener.dismissLine();
            }

        }
    };

    public void stopVoice(){
        if(mCatchVoiceData == null){
            return;
        }
        mCatchVoiceData.clear();
    }



    public NewVoiceView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initAttrs(context, attrs);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mCancelColor = ContextCompat.getColor(context, R.color.voice_view_cancel);
        mPaint.setColor(mColor);
        mPaint.setStrokeWidth(mWidth);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
    }

    private void initAttrs(Context context, @Nullable AttributeSet attrs) {
        if (attrs != null) {
            TypedArray mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.VoiceView);
            mColor = mTypedArray.getColor(R.styleable.VoiceView_color, Color.GREEN);
            mSpaceBetween = mTypedArray.getDimension(R.styleable.VoiceView_space_between, 8);
            mWidth = mTypedArray.getDimension(R.styleable.VoiceView_width, 8);
            mTypedArray.recycle();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (FirstDraw) {
            mTotalCount = (int) (getWidth() / (mSpaceBetween + mWidth) / 2) - 2;
            voiceHeight = getHeight() / FB;
            for (int i = 0; i < mTotalCount; i++) {
                mVoiceData.add(1);
            }
            FirstDraw = false;
        }

        float middleX = getWidth() / 2;
        float middleY = getHeight() / 2;
        if(!isShowLine && isAllDeng()){
            return;
        }
        for (int i = 0; i < mTotalCount; i++) {
            canvas.drawLine(middleX + (mSpaceBetween + mWidth) + (mSpaceBetween + mWidth) * i, middleY - getVoiceHeight(i),
                    middleX + (mSpaceBetween + mWidth) + (mSpaceBetween + mWidth) * i, middleY + getVoiceHeight(i), mPaint);
            canvas.drawLine(middleX - (mSpaceBetween + mWidth) - (mSpaceBetween + mWidth) * i, middleY - getVoiceHeight(i),
                    middleX - (mSpaceBetween + mWidth) - (mSpaceBetween + mWidth) * i, middleY + getVoiceHeight(i), mPaint);
        }

    }

    private int getVoiceHeight(int i) {
        try {
            return mVoiceData.get(i) * voiceHeight;
        } catch (Exception e) {
            return voiceHeight;
        }
    }

    public void setVoiceLevel(int voiceLevel) {
        if(voiceLevel == 0){
            return;
        }
        voiceLevel = voiceLevel / 2;
        if(voiceLevel == 0){
            voiceLevel = 1;
        }
        mCatchVoiceData.add(voiceLevel);
        if (!isThreadStart) {
            isThreadStart = true;
            circulationVoice();
        }
    }

    private void moveList(int level) {
        if(level > 3){
            level-=2;
        }
        mVoiceData.remove(mVoiceData.size() - 1);
        mVoiceData.add(0, level);
    }


    private void circulationVoice() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (isThreadStart) {
                    try {
                        Thread.sleep(mDrawLineTime);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    mHander.sendEmptyMessage(0);
                }
            }
        }).start();
    }

    public void emptyVoice(){
        isThreadStart = false;
        mCatchVoiceData.clear();
        mVoiceData.clear();
        for (int i = 0; i < mTotalCount; i++) {
            mVoiceData.add(1);
        }
    }

    /**
     * 循环是否结束，也就是是否列表中所有的值都相等且相等于初始值
     *
     * @return true:都相等    false:存在不相等的值
     */
    private Boolean isAllDeng() {
        int i = 1;
        for (Integer data : mVoiceData) {
            if (i != data) {
                return  false;
            }
        }
        return true;
    }


    public void exit(){
        isExit = true;
    }

    /*public void setIsShowLine(boolean isShowLine){
        this.isShowLine = isShowLine;
        if(!isShowLine && isAllDeng() && mDismissLineListener != null){
            mDismissLineListener.dismissLine();
        }
        invalidate();
    }*/

    private DismissLineListener mDismissLineListener;
    public interface DismissLineListener{
        void dismissLine();
    }

    public void setDismissLineListener(DismissLineListener mDismissLineListener) {
        this.mDismissLineListener = mDismissLineListener;
    }

    public void setCancel(boolean isCancel) {
        mPaint.setColor(isCancel ? mCancelColor : mColor);
        invalidate();
    }
}
